package listeners;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextPane;
import javax.swing.filechooser.FileNameExtensionFilter;

import view.DrawPanel;
import view.PictureModel;

import model.DataModel;
import model.DataReadWrite;

public class OpenListener implements ActionListener{
	private JFrame frame;
	private PictureModel pictureModel;
	private DrawPanel paint;
	private JTextPane textPane;
	public OpenListener(JFrame frame,PictureModel pictureModel,DrawPanel paint,JTextPane textPane){
		this.frame = frame;
		this.pictureModel = pictureModel;
		this.paint = paint;
		this.textPane = textPane;
	}
	@Override
	public void actionPerformed(ActionEvent arg0) {
		textPane.setText("");
		JFileChooser fc = new JFileChooser();
		fc.setFileFilter(new FileNameExtensionFilter("fcd", "FCD"));
		fc.setCurrentDirectory(new File("/"));
		int retVal = fc.showOpenDialog(frame);
		if (retVal == JFileChooser.APPROVE_OPTION) {
			File file = fc.getSelectedFile();
			try {
				DataModel model = DataReadWrite.readFlowchart(file);
				pictureModel.setBlocks(model.getBlocks());
				pictureModel.setLines(model.getLines());
				paint.clear();
				pictureModel.draw();
				
			} catch (Exception e) {
				JOptionPane.showMessageDialog(frame, "Invalid save operation",
						"Error", JOptionPane.ERROR_MESSAGE);
			}
		}
		
	}
	
}
